package scatter.grid.rest.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.util.Assert;
import scatter.grid.pojo.po.Grid;
import scatter.common.rest.service.IBaseService;
import scatter.grid.pojo.form.GridAddForm;
import scatter.grid.pojo.form.GridUpdateForm;
import scatter.grid.pojo.form.GridPageQueryForm;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 宫格配置表，主要用于app使用宫格的可配置场景 服务类
 * </p>
 *
 * @author yw
 * @since 2021-10-25
 */
public interface IGridService extends IBaseService<Grid> {


	/**
	 * 可用宫格列表
	 * @param groupFlags 分组标识，支持以逗号分隔的多个
	 * @return
	 */
	default List<Grid> listAvailable(String groupFlags){
		List<String> groupFlagList = Optional.ofNullable(groupFlags).map(item ->item.split(",")).map(item -> newArrayList(item)).orElse(null);
		List<Grid> result = list(Wrappers.<Grid>lambdaQuery()
				.eq(Grid::getIsDisabled,false)
				.in(!isEmpty(groupFlagList),Grid::getGroupFlag,groupFlagList)
				// 后面加 id ，稳定排序
				.orderByAsc(Grid::getSeq).orderByAsc(Grid::getId)
		);
		// 过滤时间，时间为空的算永久
		if (!isEmpty(result)) {
			result = result.stream().filter(item -> {
				LocalDateTime start  = Optional.ofNullable(item.getStartAt()).orElse(LocalDateTimeUtil.of(DateUtil.yesterday()));
				LocalDateTime end  = Optional.ofNullable(item.getEndAt()).orElse(LocalDateTimeUtil.of(DateUtil.tomorrow()));
				return LocalDateTime.now().isAfter(start) && LocalDateTime.now().isBefore(end);
			}).collect(Collectors.toList());
		}
		return result;
	}
}
